<!-- 折线图 -->

<!DOCTYPE html>
<head>
<meta charset="utf-8">
<script src="http://gallerybox.echartsjs.com/dep/echarts/latest/echarts.min.js"></script>
<script type="text/javascript" src="js/jquery.min.js"></script>
<script type="text/javascript" src="js/moment.min.js"></script>
<script type="text/javascript">
    $(function() {
        var showEcharts = function(_dataTitle, timePoint, dataValues, elementById) {
            var seriesArray = [];

            for (var i = 0; i < _dataTitle.length; i++) {
                seriesArray.push({
                    yAxisIndex : i,
                    name : _dataTitle[i],
                    type : 'line',
                    smooth : true,
                    data : dataValues[i],
                    markLine : {
                        data : [ {
                            type : 'average'
                        } ]
                    }
                });
            }

            var yAxisArray = [];

            for (var i = 0; i < _dataTitle.length; i++) {
                var yAxisShow = i <= 5;

                var _yAxis = {
                    show : yAxisShow,
                    type : 'value',
                    position : 'left',
                    offset : 30 * i,
                    min : 0,
                    boundaryGap : [ ((100 / _dataTitle.length) * i) + '%', ((100 / _dataTitle.length) * (i+1)) +'%' ]
                };

                yAxisArray.push(_yAxis);
            }

            // 没有数据的曲线默认隐藏
            var legendSelected={};
            for (var i = 0; i < _dataTitle.length; i++) {
                legendSelected[_dataTitle[i]] = false;

                for(var j = 0; j < dataValues[i].length; j++){
                    if(dataValues[i][j] > 0){
                        legendSelected[_dataTitle[i]] = true;
                        break;
                    }
                }
            }

            var option = {
                legend : {
                    data : _dataTitle,
                    selected: legendSelected
                },

                tooltip : {
                    trigger : 'axis'
                },

                dataZoom : {
                    show : true
                },

                xAxis : [ {
                    type : 'category',
                    data : timePoint
                } ],

                yAxis : yAxisArray,

                series : seriesArray
            };

            // 基于准备好的dom，初始化echarts图表 
            var myChart = echarts.init(document.getElementById(elementById));

            // 为echarts对象加载数据 
            myChart.setOption(option);

            $("#span-5").html(" [done] ");
        };

        // 合并数据
        var mergeData = function(_data, _count){
            console.log("mergeData, old data.len = " + _data.timePoints.length + ", _count = " + _count);

            if (_count < 10 || _data.timePoints.length < _count) { // 数据少 跳出
                $("#span-4").html(" [merge后" + _data.timePoints.length+"] ");
                return _data;
            }

            var _timePointsNew = [];
            var _dataValuesNew = [];

            for(var i=0; i<_data.timePoints.length; i=i+2){
                _timePointsNew.push(_data.timePoints[i]);
            }

            for(var j=0; j<_data.dataValues.length ; j++) { // 每一条曲线
                _dataValuesNew.push(new Array()); // 初始化新的数据数组
            }

            for(var k=0; k<_data.dataValues.length ; k++) { // 每一条曲线
                for(var m=0; m<_data.dataValues[k].length; m=m+2) { // 曲线每个点
                    var _value = (_data.dataValues[k][m] + _data.dataValues[k][m+1])/2 ;
                    _dataValuesNew[k].push(_value);
                }
            }

            return mergeData({"timePoints": _timePointsNew, "dataValues":_dataValuesNew}, _count);
        };

        // 数据取整
        var roundData = function(_data){
            for(var k=0; k<_data.dataValues.length ; k++) { // 每一条曲线
                for(var m=0; m<_data.dataValues[k].length; m++) { // 曲线每个点
                    _data.dataValues[k][m] =Math.ceil( _data.dataValues[k][m]) ; // 只入不舍
                }
            }

            return _data;
        };

        var loadDataAndShowEcharts = function(){
            $("#span-5").html(" [ajax] ");

            $.getJSON("line-graph.json" + location.search, function(responseJson) {
                if ( !!responseJson.error ) {
                    $("#echarts-1").html("<h1>error : " + responseJson.error + "</h1>");
                    return ; 
                }

                var _dataTitles = [];

                var _timePoints = [];

                var timePointMin;
                var timePointMax;
        
                // 获取起止时间
                if(!!responseJson.data){
                    for (var key in responseJson.data) {
                        var unixMilliseconds = moment(key, "YYYYMMDDHHmm").format("X");
                        var unixMinute = Number(unixMilliseconds) / 60;
        
                        if (!timePointMin || timePointMin > unixMinute) {
                            timePointMin = unixMinute;
                        }
                        if (!timePointMax || timePointMax < unixMinute) {
                            timePointMax = unixMinute;
                        }
                    }
                }

                var _dataValues = [];

                // 获取Title
                if(!!responseJson.meta){
                    for ( var key in responseJson.meta) {
                        _dataTitles.push(responseJson.meta[key]);
                        _dataValues.push(new Array());
                    }
                }

                // 中间某些时刻可能无数据
                for (var i = timePointMin; i <= timePointMax; i++) {
                    var timeKey = moment(i*60*1000).format("YYYYMMDDHHmm");
                    var timeDisplay = moment(i*60*1000).format("YYYY-MM-DD HH:mm");
        
                    _timePoints.push(timeDisplay);
                    var dataEach = responseJson.data[timeKey];
        
                    if (!!dataEach) {
                        for (var j = 0; j < _dataTitles.length; j++) {
                            _dataValues[j].push(Number(dataEach[j]));
                        }
                    } else {
                        for (var j = 0; j < _dataTitles.length; j++) {
                            _dataValues[j].push(0);
                        }
                    }
                }

                $("#span-3").html(" [merge前 " + _timePoints.length +"] ");

                // 数据过多，合并
                var data_count = $("#data_count").val();
                var _mergedData = mergeData({"timePoints": _timePoints, "dataValues": _dataValues}, data_count); // 合并成最多100个点

                var _mergedData = roundData(_mergedData);

                // 渲染视图
                if(_timePoints.length<1){
                    $("#echarts-1").html("<h1>NO DATA timePoints.length is 0</h1>");
                }else{
                    showEcharts(_dataTitles, _mergedData.timePoints, _mergedData.dataValues, 'echarts-1');
                    $("#span-2").html(" [数据量 " + Object.getOwnPropertyNames(responseJson.data).length+"] ");
                }
            });
        };

        // 初次加载数据
        loadDataAndShowEcharts();

        var intervalId = -1;

        // 周期性刷新
        var load_interval = $("#load_interval").val();
        if (!!load_interval && load_interval > 9) {
            intervalId = setInterval(loadDataAndShowEcharts, load_interval)
        }

        // 绑定事件
        $("#data_count").on("change", loadDataAndShowEcharts);

        // 绑定事件
        $("#load_interval").on("change", function(){
            clearInterval(intervalId);

            var load_interval = $("#load_interval").val();
            if (!!load_interval && load_interval > 9) {
                intervalId = setInterval(loadDataAndShowEcharts, load_interval)
            }

            loadDataAndShowEcharts();
        });
    });
</script>
</head>
<body>
    <!-- 为ECharts准备一个具备大小（宽高）的Dom -->
    <div id="echarts-1" style="height: 400px"><h1>loading ... </h1></div>
    <div>
        <span>
            限制个数
            <select id="data_count">
            <option value="-1">不限</option>
            <option value="100">100</option>
            <option value="200">200</option>
            <option value="500">500</option>
            <option value="1000">1000</option>
            <option value="2000">2000</option>
            <option value="5000">5000</option>
            <option value="10000">10000</option>
            <option value="20000">20000</option>
            <option value="50000">50000</option>
            </select>
        </span>
        <span>
            自动刷新周期
            <select id="load_interval">
            <option value="-1">不刷新</option>
            <option value="10000">10秒</option>
            <option value="30000">30秒</option>
            <option value="60000">1分钟</option>
            <option value="120000">2分钟</option>
            <option value="300000">5分钟</option>
            </select>
        </span>
        <span id="span-5"></span>
        <span id="span-2"></span>
        <span id="span-3"></span>
        <span id="span-4"></span>
        <a style="text-decoration: none;" href="javascript:$('#data_count').trigger('change');">手动刷新</a>
        <a style="text-decoration: none;" href="index.html">budo-graph index</a>
        <a style="text-decoration: none;" href="../../">ProviderList</a>
        <a>${(dubboProvider.toNameString())!}</a>
    </div>
</body>